﻿param($selectedWebApplication = $null, $features = @{applicationFiles=$true;})

trap [Exception]
{
	echo ""
	echo "An unhandled error has occured:"
	echo $_.Exception
	echo "When executing"
	echo $_.InvocationInfo.PositionMessage
	echo ""	$inTransaction = Get-EPiIsBulkInstalling

	$inTransaction = Get-EPiIsBulkInstalling

	if($inTransaction -eq $true)
	{
		Rollback-EPiBulkInstall
	}	
	
	break
}

$VerbosePreference = "Continue"
$ErrorActionPreference = "Continue"
$Product = "CMS"

# Load the EPiServer Common snapin if required
$snapIn = Get-PSSnapin -Name EPiServer.Install.Common.1 -ErrorAction SilentlyContinue
if ($snapIn -eq $null)
{
	Add-PSSnapin EPiServer.Install.Common.1
}

# Get the version location path of EPiServer in order to find resources
$CurrentDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$epiVersion = Get-EPiVersion -MapPath $CurrentDir

# Load the EPiServer CMS snapin if required
$snapIn = Get-PSSnapin -Name EPiServer.Install.CMS.$epiVersion -ErrorAction SilentlyContinue
if ($snapIn -eq $null)
{
	Add-PSSnapin EPiServer.Install.CMS.$epiVersion
}

$proceedWithInstall = $true

# The wizard is used for progress messages so load it even if we don't need to display it
$wizard = New-EPiCMSWizard "InstallModuleWizard" ($MyInvocation.MyCommand.Path)

$wizard.Features = $features

$epiProductInfo = Get-EPiProductInformation -ProductName $Product -ProductVersion $epiVersion
if (!$epiProductInfo.IsInstalled)
{
	throw(New-Object ApplicationException($wizard.Resources.GetString("ErrorInstallationDirectoryNotFound")))
}
$sourceTemplateFolder = [System.IO.Path]::Combine($epiProductInfo.InstallationPath, "Install\Modules\ETF")

if ($selectedWebApplication -eq $null)
{	
	$wizard.CMSVersions = Get-CompatibleProductVersions -ModuleScriptPath $MyInvocation.MyCommand.Path
	$wizard.ValidateDatabaseConnection = $true
	$wizard.Title = "Add ETF to EPiServer website"
	$proceedWithInstall = $wizard.Show()
	
	if ($proceedWithInstall)
	{
		$selectedWebApplication = $wizard.SelectedApplication		
	}
}

if ($proceedWithInstall)
{
	# Read back features
	$features = $wizard.Features
	
	$inTransaction = Get-EPiIsBulkInstalling

	if($inTransaction -eq $false)
	{
		Begin-EPiBulkInstall -SelectedSite $selectedWebApplication -RunDistributedTransaction -StartMSDTC
	}

	Set-EPiProgressStatus -status "Adding ETF to website..."

    if ($features.applicationFiles)
    {
        Set-EPiProgressStatus -status "Verifying Page Type Builder binary is present..."
        
        $ptbAssemblyPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "bin\PageTypeBuilder.dll")
    
        if(!(Test-Path $ptbAssemblyPath))
        {
            throw("Page Type Builder is required, ensure PageTypeBuilder.dll exists in the 'bin' folder.")
        }
    
        Set-EPiProgressStatus -status "Copying ETF binary to 'bin' folder..."
        
        $siteBinFolder = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "bin")
        
        Copy-EPiFiles -SourceDirectoryPath $sourceTemplateFolder -DestinationDirectoryPath $siteBinFolder -Exclude "*.ps1,*.metadata,*.xmlupdate,*.txt" -Recursive -ProgressPercent 60   	
    }
    
    if ($features.updateConfiguration)
    {
        Set-EPiProgressStatus -status "Updating web.config..."
   
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
    
    Add-EPiProgressPercentComplete -percent 40
    
    if ($features.useBritishFlag)
    {
        Set-EPiProgressStatus -status "Updating web.config to use British flag for 'en' language branch..."
    	
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.BritishFlagForEnLanguageBranch.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
    
    Add-EPiProgressPercentComplete -percent 30
    
    if ($features.addLoginLogo)
    {
    	Set-EPiProgressStatus -status "Updating web.config to display Ted & Gustaf logo on EPiServer login page..."
        
    	$modificationFile = [System.IO.Path]::Combine($sourceTemplateFolder, "ETF.TedGustafLoginLogo.xmlupdate")
    	$targetWebConfigPath = [System.IO.Path]::Combine($selectedWebApplication.PhysicalPath, "web.config")
        
        Update-EPiXmlFile -ModificationFilePath $modificationFile -TargetFilePath $targetWebConfigPath
    }
	
	Add-EPiProgressPercentComplete -percent 25

	if($inTransaction -eq $false)
	{
		Commit-EPiBulkInstall
		Add-EPiProgressPercentComplete -percent 5
	}

	Set-EPiProgressStatus -status "ETF installer completed."
}

# SIG # Begin signature block
# MIILTAYJKoZIhvcNAQcCoIILPTCCCzkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUagsK3Xo0/ov1+YBTblkYmaf0
# uw2gggi3MIIEEzCCAvugAwIBAgIQX8p1j1CaX9ue2wSkib7rmDANBgkqhkiG9w0B
# AQUFADBKMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMVGhhd3RlLCBJbmMuMSQwIgYD
# VQQDExtUaGF3dGUgQ29kZSBTaWduaW5nIENBIC0gRzIwHhcNMTExMTA5MDAwMDAw
# WhcNMTMwNTAzMjM1OTU5WjBpMQswCQYDVQQGEwJTRTESMBAGA1UECBMJU3RvY2to
# b2xtMRIwEAYDVQQHEwlTdG9ja2hvbG0xGDAWBgNVBAoUD1RlZCAmIEd1c3RhZiBB
# QjEYMBYGA1UEAxQPVGVkICYgR3VzdGFmIEFCMIIBIjANBgkqhkiG9w0BAQEFAAOC
# AQ8AMIIBCgKCAQEAxBv9qP5pGtaUTrD33yIphwzIGkdhKJj/C4qhK28H16SArrJL
# o2TQpxK6kIylvoLBVgi1VXcwshA9nG4Nyb2Hr7dv3EakCR48xhL6XmZxkykum/ut
# uWIHc0WvJDAFTk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